package com.qxzn.app.medicalhealth.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.alibaba.fastjson.JSONObject;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.CircleCrop;
import com.bumptech.glide.request.RequestOptions;
import com.github.jdsjlzx.interfaces.OnItemClickListener;
import com.github.jdsjlzx.recyclerview.LRecyclerView;
import com.github.jdsjlzx.recyclerview.LRecyclerViewAdapter;
import com.qxzn.app.api.api.HttpRequest;
import com.qxzn.app.bean.MedicineRemindDetailBean;
import com.qxzn.app.bean.MedicineRemindDetailListBean;
import com.qxzn.app.medicalhealth.R;
import com.qxzn.app.medicalhealth.R2;
import com.qxzn.app.medicalhealth.adapter.RemindDetailAdapter;
import com.qxzn.app.page.BaseActivity;
import com.qxzn.app.util.AppUtil;
import com.qxzn.app.util.SystemUtil;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import okhttp3.MediaType;
import okhttp3.RequestBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * 吃药提醒详情
 */
public class RemindDetailActivity extends BaseActivity {

    @BindView(R2.id.lrv_medicine)
    LRecyclerView lrvMedicine;
    private LRecyclerViewAdapter recyclerViewAdapter;
    private RemindDetailAdapter adapter;
    private List<MedicineRemindDetailListBean> dataList = new ArrayList<>();
    private Call<MedicineRemindDetailBean> call;
    private HeadViewHolder headHolder;
    private FootViewHolder footViewHolder;
    private MedicineRemindDetailBean.DataBean dataBean;

    @Override
    protected int initLayout() {
        return R.layout.activity_remind_detail;
    }

    @Override
    protected void initView() {
        lrvMedicine.setLayoutManager(new LinearLayoutManager(this));
        adapter = new RemindDetailAdapter(this, dataList);
        recyclerViewAdapter = new LRecyclerViewAdapter(adapter);
        lrvMedicine.setAdapter(recyclerViewAdapter);
        recyclerViewAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                AppUtil.showLog("点击位置：" + position);
            }
        });
        lrvMedicine.setPullRefreshEnabled(false);
        View headView = LayoutInflater.from(this).inflate(R.layout.item_remind_detail_head, (ViewGroup) findViewById(android.R.id.content), false);
        headHolder = new HeadViewHolder(headView);
        recyclerViewAdapter.addHeaderView(headView);
        View footView = LayoutInflater.from(this).inflate(R.layout.item_remind_detail_foot, (ViewGroup) findViewById(android.R.id.content), false);
        footViewHolder = new FootViewHolder(footView);
        recyclerViewAdapter.addFooterView(footView);
    }

    @Override
    protected void iniTitleBar() {
        tv_title.setText("吃药提醒详情");
        TextView textView = new TextView(this);
        textView.setId(R.id.tv_delete);
        textView.setText("编辑");
        textView.setTextColor(getResources().getColor(R.color.white));
        textView.setOnClickListener(this);
        ll_right_bar.addView(textView);
    }

    @Override
    protected void initData(Bundle savedInstanceState) {
//        for (int i = 0; i < 3; i++) {
//            dataList.add(i + "");
//        }
//        recyclerViewAdapter.notifyDataSetChanged();
        if (TextUtils.isEmpty(getIntent().getStringExtra("id"))) {
            AppUtil.showToast(RemindDetailActivity.this, "参数有误");
            finish();
            return;
        }
        getMedicineRemindTime(getIntent().getStringExtra("id"));
    }

    @Override
    public void onClick(View view) {
        super.onClick(view);
        if (view.getId() == R.id.tv_delete) {
            if (dataBean != null) {
                startActivityForResult(new Intent(RemindDetailActivity.this, EditRemindActivity.class).putExtra("edit_data", dataBean), 1);
            } else {
                AppUtil.showToast(RemindDetailActivity.this, "数据有误");
            }
        }
    }

    private void getMedicineRemindTime(String id) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("id", id);
        RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), jsonObject.toJSONString());
        call = HttpRequest.getService().getMedicineRemindDetail(body);
        call.enqueue(new Callback<MedicineRemindDetailBean>() {
            @Override
            public void onResponse(Call<MedicineRemindDetailBean> call, Response<MedicineRemindDetailBean> response) {
                MedicineRemindDetailBean bean = response.body();
                if (bean != null && bean.getCode() == 200) {
                    if (bean.getData() != null) {
                        dataBean = bean.getData();
                        if (dataBean != null) {
                            String remark = dataBean.getNiname();
                            if (!TextUtils.isEmpty(remark)) {
                                remark = "(" + remark + ")";
                            } else {
                                remark = "";
                            }
                            headHolder.tvName.setText(dataBean.getUsername() + remark);
                            headHolder.tvAge.setText("年龄：" + dataBean.getAge() + "岁");
                            Glide.with(RemindDetailActivity.this).load(HttpRequest.BASE_URL + dataBean.getHeadportrait()).apply(RequestOptions.bitmapTransform(new CircleCrop()).placeholder(R.mipmap.logo).error(R.mipmap.logo)).into(headHolder.ivHead);
                            footViewHolder.ivRecord.setOnClickListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    if (TextUtils.isEmpty(dataBean.getRingtone())) {
                                        AppUtil.showToast(RemindDetailActivity.this, "未设置提醒铃声");
                                    } else {
                                        SystemUtil.playMedia(HttpRequest.BASE_URL + dataBean.getRingtone());
                                    }
                                }
                            });
                            String takeMedicineTime = dataBean.getMedicinetime();
                            if (!TextUtils.isEmpty(takeMedicineTime)) {
                                String[] timeList = takeMedicineTime.split(",");
                                if (timeList != null) {
                                    for (String s : timeList) {
                                        dataList.add(new MedicineRemindDetailListBean(s, dataBean.getResultdetails()));
                                    }
                                    adapter.notifyDataSetChanged();
                                    recyclerViewAdapter.notifyDataSetChanged();
                                }
                            }
                        }
                    }
                    return;
                }
                if (bean != null && !TextUtils.isEmpty(bean.getMsg())) {
                    AppUtil.showToast(RemindDetailActivity.this, bean.getMsg());
                } else {
                    AppUtil.showToast(RemindDetailActivity.this, "网络错误，请稍后再试！");
                }
                finish();
            }

            @Override
            public void onFailure(Call<MedicineRemindDetailBean> call, Throwable t) {
                AppUtil.showToast(RemindDetailActivity.this, "网络错误，请稍后再试！");
                finish();
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == 1) {
                finish();
            }
        }
    }

    static class HeadViewHolder {
        @BindView(R2.id.tv_name)
        TextView tvName;
        @BindView(R2.id.tv_age)
        TextView tvAge;
        @BindView(R2.id.iv_head)
        ImageView ivHead;

        HeadViewHolder(View view) {
            ButterKnife.bind(this, view);
        }
    }

    static class FootViewHolder {
        @BindView(R2.id.iv_record)
        ImageView ivRecord;

        FootViewHolder(View view) {
            ButterKnife.bind(this, view);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (call != null) {
            call.cancel();
        }
    }

}
